'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useSession } from 'next-auth/react';
import AppHeader from '@/components/ui/app-header';
import {
  UsersIcon,
  ChartBarIcon,
  ClockIcon,
  DocumentTextIcon,
  PencilIcon,
  ArrowPathIcon,
  CheckCircleIcon,
  ExclamationCircleIcon,
  ClipboardDocumentListIcon,
} from '@heroicons/react/24/outline';

// 项目状态标签组件
const StatusBadge = ({ status }: { status: string }) => {
  switch (status) {
    case 'completed':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
          <CheckCircleIcon className="mr-1 h-4 w-4" />
          已完成
        </span>
      );
    case 'in-progress':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
          <ArrowPathIcon className="mr-1 h-4 w-4" />
          进行中
        </span>
      );
    case 'planning':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
          <ClockIcon className="mr-1 h-4 w-4" />
          规划中
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          {status}
        </span>
      );
  }
};

// 项目类型定义
interface Project {
  id: string;
  name: string;
  description?: string;
  createdAt: string;
  updatedAt: string;
  owner?: {
    id: string;
    name: string;
    avatar?: string;
  };
  members?: {
    id: string;
    name: string;
    avatar?: string;
    role: string;
  }[];
  status: string;
  tags?: string[];
}

export default function ProjectDetailPage() {
  const router = useRouter();
  const params = useParams();
  const projectId = params.id as string;
  const { data: session, status: authStatus } = useSession();
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 获取项目数据
  useEffect(() => {
    const fetchProject = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(`/api/project?id=${projectId}`);
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.success) {
          setProject(data.data);
        } else {
          throw new Error(data.message || '获取项目失败');
        }
      } catch (err: any) {
        console.error('获取项目详情失败:', err);
        setError(err.message || '获取项目详情失败');
      } finally {
        setLoading(false);
      }
    };
    
    if (authStatus === 'authenticated' && projectId) {
      fetchProject();
    } else if (authStatus === 'unauthenticated') {
      router.push('/auth/login');
    }
  }, [authStatus, projectId, router]);

  // 导航链接
  const navLinks = [
    { 
      name: '概览', 
      href: `/project/${projectId}`, 
      icon: <DocumentTextIcon className="h-5 w-5" />,
      current: true 
    },
    { 
      name: '看板', 
      href: `/project/${projectId}/board`, 
      icon: <ClipboardDocumentListIcon className="h-5 w-5" />,
      current: false 
    },
    { 
      name: '编辑器', 
      href: `/project/${projectId}/editor`, 
      icon: <PencilIcon className="h-5 w-5" />,
      current: false 
    },
    { 
      name: '团队', 
      href: `/project/${projectId}/team`, 
      icon: <UsersIcon className="h-5 w-5" />,
      current: false 
    },
    { 
      name: '数据统计', 
      href: `/project/${projectId}/stats`, 
      icon: <ChartBarIcon className="h-5 w-5" />,
      current: false 
    },
    { 
      name: '活动记录', 
      href: `/project/${projectId}/activity`, 
      icon: <ClockIcon className="h-5 w-5" />,
      current: false 
    },
  ];

  // 如果未登录，显示加载中
  if (authStatus === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-pulse text-gray-500">加载中...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        {loading ? (
          <div className="flex justify-center py-12">
            <div className="animate-pulse text-gray-500">加载项目中...</div>
          </div>
        ) : error ? (
          <div className="bg-red-50 p-4 rounded-md">
            <div className="flex">
              <div className="flex-shrink-0">
                <ExclamationCircleIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800">加载项目时出错</h3>
                <div className="mt-2 text-sm text-red-700">
                  <p>{error}</p>
                </div>
              </div>
            </div>
          </div>
        ) : project ? (
          <>
            <AppHeader
              title={project.name}
              subtitle={project.description}
              actions={
                <StatusBadge status={project.status} />
              }
            />

            {/* 项目导航 */}
            <div className="mt-6 bg-white shadow rounded-lg overflow-hidden">
              <div className="sm:hidden">
                <label htmlFor="project-navigation" className="sr-only">
                  选择项目导航
                </label>
                <select
                  id="project-navigation"
                  name="project-navigation"
                  className="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                  defaultValue={navLinks.find(link => link.current)?.name}
                  onChange={(e) => {
                    const selected = navLinks.find(link => link.name === e.target.value);
                    if (selected) {
                      router.push(selected.href);
                    }
                  }}
                  aria-label="项目导航"
                >
                  {navLinks.map((link) => (
                    <option key={link.name} value={link.name}>
                      {link.name}
                    </option>
                  ))}
                </select>
              </div>
              <div className="hidden sm:block">
                <nav className="flex" aria-label="Tabs">
                  {navLinks.map((link) => (
                    <Link
                      key={link.name}
                      href={link.href}
                      className={`
                        px-4 py-3 text-sm font-medium flex items-center
                        ${link.current
                          ? 'border-b-2 border-[var(--primary-color)] text-[var(--primary-color)]'
                          : 'text-gray-500 hover:text-gray-700 hover:border-gray-300'
                        }
                      `}
                      aria-current={link.current ? 'page' : undefined}
                    >
                      <span className="mr-2">{link.icon}</span>
                      {link.name}
                    </Link>
                  ))}
                </nav>
              </div>
            </div>

            {/* 项目详情 */}
            <div className="mt-6 bg-white shadow rounded-lg p-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="md:col-span-2">
                  <h3 className="text-lg font-medium text-gray-900">项目详情</h3>
                  <div className="mt-4">
                    <dl className="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2">
                      <div className="sm:col-span-1">
                        <dt className="text-sm font-medium text-gray-500">项目名称</dt>
                        <dd className="mt-1 text-sm text-gray-900">{project.name}</dd>
                      </div>
                      <div className="sm:col-span-1">
                        <dt className="text-sm font-medium text-gray-500">创建时间</dt>
                        <dd className="mt-1 text-sm text-gray-900">
                          {new Date(project.createdAt).toLocaleDateString('zh-CN')}
                        </dd>
                      </div>
                      <div className="sm:col-span-1">
                        <dt className="text-sm font-medium text-gray-500">状态</dt>
                        <dd className="mt-1 text-sm text-gray-900">
                          <StatusBadge status={project.status} />
                        </dd>
                      </div>
                      <div className="sm:col-span-1">
                        <dt className="text-sm font-medium text-gray-500">最近更新</dt>
                        <dd className="mt-1 text-sm text-gray-900">
                          {new Date(project.updatedAt).toLocaleDateString('zh-CN')}
                        </dd>
                      </div>
                      <div className="sm:col-span-2">
                        <dt className="text-sm font-medium text-gray-500">项目描述</dt>
                        <dd className="mt-1 text-sm text-gray-900">
                          {project.description || '暂无描述'}
                        </dd>
                      </div>
                      <div className="sm:col-span-2">
                        <dt className="text-sm font-medium text-gray-500">标签</dt>
                        <dd className="mt-1 text-sm text-gray-900">
                          {project.tags && project.tags.length > 0 ? (
                            <div className="flex flex-wrap gap-2">
                              {project.tags.map(tag => (
                                <span
                                  key={tag}
                                  className="inline-flex items-center px-2.5 py-0.5 rounded-md text-sm font-medium bg-gray-100 text-gray-800"
                                >
                                  {tag}
                                </span>
                              ))}
                            </div>
                          ) : (
                            '暂无标签'
                          )}
                        </dd>
                      </div>
                    </dl>
                  </div>
                </div>
                <div>
                  <h3 className="text-lg font-medium text-gray-900">团队成员</h3>
                  <div className="mt-4">
                    <ul className="divide-y divide-gray-200">
                      {project.members && project.members.length > 0 ? (
                        project.members.map((member) => (
                        <li key={member.id} className="py-3 flex items-center">
                          <div className="h-10 w-10 rounded-full overflow-hidden bg-gray-100">
                            {member.avatar ? (
                              <Image
                                src={member.avatar}
                                alt={member.name}
                                width={40}
                                height={40}
                                className="h-full w-full object-cover"
                              />
                            ) : (
                              <div className="h-full w-full flex items-center justify-center bg-gray-300 text-gray-600 text-sm font-medium">
                                {member.name.substring(0, 2).toUpperCase()}
                              </div>
                            )}
                          </div>
                          <div className="ml-3">
                            <p className="text-sm font-medium text-gray-900">{member.name}</p>
                            <p className="text-sm text-gray-500">
                              {member.role === 'owner' ? '所有者' : 
                               member.role === 'editor' ? '编辑者' : '查看者'}
                            </p>
                          </div>
                        </li>
                        ))
                      ) : (
                        <li className="py-3">暂无团队成员</li>
                      )}
                    </ul>
                    <div className="mt-4">
                      <Link
                        href={`/project/${projectId}/team`}
                        className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
                      >
                        查看全部团队
                      </Link>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 快速访问卡片 */}
            <div className="mt-6 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
              <div className="bg-white shadow rounded-lg overflow-hidden">
                <div className="p-5">
                  <div className="flex items-center">
                    <div className="flex-shrink-0">
                      <ClipboardDocumentListIcon className="h-6 w-6 text-[var(--primary-color)]" />
                    </div>
                    <div className="ml-5 w-0 flex-1">
                      <dl>
                        <dt className="text-sm font-medium text-gray-500 truncate">项目看板</dt>
                        <dd>
                          <div className="text-lg font-medium text-gray-900">查看任务进度</div>
                        </dd>
                      </dl>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-5 py-3">
                  <div className="text-sm">
                    <Link
                      href={`/project/${projectId}/board`}
                      className="font-medium text-[var(--primary-color)] hover:text-[var(--primary-hover)]"
                    >
                      进入看板
                    </Link>
                  </div>
                </div>
              </div>

              <div className="bg-white shadow rounded-lg overflow-hidden">
                <div className="p-5">
                  <div className="flex items-center">
                    <div className="flex-shrink-0">
                      <PencilIcon className="h-6 w-6 text-[var(--primary-color)]" />
                    </div>
                    <div className="ml-5 w-0 flex-1">
                      <dl>
                        <dt className="text-sm font-medium text-gray-500 truncate">协作编辑</dt>
                        <dd>
                          <div className="text-lg font-medium text-gray-900">实时文档协作</div>
                        </dd>
                      </dl>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-5 py-3">
                  <div className="text-sm">
                    <Link
                      href={`/project/${projectId}/editor`}
                      className="font-medium text-[var(--primary-color)] hover:text-[var(--primary-hover)]"
                    >
                      打开编辑器
                    </Link>
                  </div>
                </div>
              </div>

              <div className="bg-white shadow rounded-lg overflow-hidden">
                <div className="p-5">
                  <div className="flex items-center">
                    <div className="flex-shrink-0">
                      <ChartBarIcon className="h-6 w-6 text-[var(--primary-color)]" />
                    </div>
                    <div className="ml-5 w-0 flex-1">
                      <dl>
                        <dt className="text-sm font-medium text-gray-500 truncate">项目统计</dt>
                        <dd>
                          <div className="text-lg font-medium text-gray-900">查看数据分析</div>
                        </dd>
                      </dl>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-5 py-3">
                  <div className="text-sm">
                    <Link
                      href={`/project/${projectId}/stats`}
                      className="font-medium text-[var(--primary-color)] hover:text-[var(--primary-hover)]"
                    >
                      查看统计
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          </>
        ) : (
          <div className="flex flex-col items-center justify-center py-12">
            <h3 className="text-lg font-medium text-gray-900">项目不存在</h3>
            <p className="mt-2 text-sm text-gray-500">
              您请求的项目不存在或已被删除
            </p>
            <div className="mt-6">
              <button
                type="button"
                onClick={() => router.push('/project')}
                className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none"
              >
                返回项目列表
              </button>
            </div>
          </div>
        )}
      </main>
    </div>
  );
} 